package house.controller;

import com.alibaba.fastjson.JSONObject;
import house.entity.Device;
import house.entity.House;
import house.entity.HousePic;
import house.entity.Res;
import house.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping(value = "/house")
public class HouseController {

    @Autowired
    private HouseService houseService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestBody String json, HttpServletResponse response) throws IOException {
        Res res = null;
        try {
            JSONObject req = JSONObject.parseObject(json);
            House house = req.getObject("house", House.class);
            List<Device> devices = req.getJSONArray("devices").toJavaList(Device.class);
            List<HousePic> housePics = req.getJSONArray("pics").toJavaList(HousePic.class);
            res = houseService.createHouse(house, devices, housePics);
        } catch (Exception e) {
            response.sendError(400, e.getMessage());
        }

        return JSONObject.toJSONString(res);
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public String info(@RequestParam(value = "id") String id, HttpServletResponse response) throws IOException {
        Res res = null;
        try {
            Integer houseId = Integer.valueOf(id);
            res = houseService.findHouse(houseId);
        } catch (Exception e) {
            response.sendError(400, e.getMessage());
        }

        return JSONObject.toJSONString(res);
    }

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ResponseBody
    public String search(@RequestBody String json, HttpServletResponse response) throws IOException {
        Res res = null;
        try {
            JSONObject req = JSONObject.parseObject(json);
            House house = req.getObject("house", House.class);
            float area = req.getFloatValue("area");
            float price = req.getFloatValue("price");
            res = houseService.filterHouse(house, area, price);
        } catch (Exception e) {
            response.sendError(400, e.getMessage());
        }

        return JSONObject.toJSONString(res);
    }
}
